package com.example.taobao

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.Glide.init
import kotlinx.android.synthetic.main.activity_gouwuche.*
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.Thread.sleep
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import java.text.DecimalFormat
import kotlin.concurrent.thread


class Fragment_gouwuche : Fragment() {

    val search = "search"
    var total=0.0//总价
    var choosenum=0//选中的件数
    var itemcount=0//宝贝总件数
    var buy_succeed=false
    val format = DecimalFormat("0.##")//保留两位小数


    private var gooselist: ArrayList<gooseInfo> = ArrayList<gooseInfo>()

    val handle = @SuppressLint("HandlerLeak")
    object : Handler()
    {
        override fun handleMessage(msg: Message) {
            gooselist = msg.obj as ArrayList<gooseInfo>
            //使用Recycler
            val mRecyclerView = activity?.findViewById<RecyclerView>(R.id.rv_store)
            val layoutManager = LinearLayoutManager(context)
            if (mRecyclerView != null) {
                mRecyclerView.layoutManager = layoutManager
            }
            val adapter = context?.let { gooseAdapter(it,gooselist) }
            if (mRecyclerView != null) {
                mRecyclerView.adapter = adapter
            }
            if (adapter != null) {
                itemcount = adapter.itemCount
            }//获取宝贝总数
            activity?.runOnUiThread {
                total_goose_num.text = "共${itemcount}件宝贝"
                tv_settlement.text = "结算（${choosenum}）"
                tv_show_price.text = "共计￥${total}"
            }
        }
    }
    fun resh()
    {
        val mRecyclerView = activity?.findViewById<RecyclerView>(R.id.rv_store)
        val layoutManager = LinearLayoutManager(context)
        if (mRecyclerView != null) {
            mRecyclerView.layoutManager = layoutManager
        }
        val adapter = context?.let { gooseAdapter(it,gooselist) }
        if (mRecyclerView != null) {
            mRecyclerView.adapter = adapter
        }
        if (adapter != null) {
            itemcount = adapter.itemCount
        }//获取宝贝总数
        activity?.runOnUiThread {
            total_goose_num.text = "共${itemcount}件宝贝"
            tv_settlement.text = "结算（${choosenum}）"
            tv_show_price.text = "共计￥${total}"
        }
    }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_gouwuche, container, false)
    }



    private val myActivityLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ activityResult ->
        val mRecyclerView = activity?.findViewById<RecyclerView>(R.id.rv_store)
        val layoutManager = LinearLayoutManager(context)
        if (mRecyclerView != null) {
            mRecyclerView.layoutManager = layoutManager
        }
        val adapter = context?.let { gooseAdapter(it, gooselist) }
        if(activityResult.resultCode == Activity.RESULT_OK){
            //val result = activityResultF.data?.getStringExtra("result")
            Toast.makeText(context, "购买成功，宝贝正在路上~", Toast.LENGTH_SHORT).show()
            buy_succeed=true
            delete()
            buy_succeed=false
            activity?.runOnUiThread {
                tv_settlement.text="结算（${choosenum}）"
                tv_show_price.text="共计￥${format.format(total)}"
                total_goose_num.text = "共${adapter?.itemCount}件宝贝"

            }
            adapter?.notifyDataSetChanged()
        }
    }
//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        val mRecyclerView = activity?.findViewById<RecyclerView>(R.id.rv_store)
//        val layoutManager = LinearLayoutManager(context)
//        if (mRecyclerView != null) {
//            mRecyclerView.layoutManager = layoutManager
//        }
//        val adapter = context?.let { gooseAdapter(it, gooselist) }
//        when(requestCode){
//            1->if(resultCode == AppCompatActivity.RESULT_OK){
//                Toast.makeText(context, "购买成功，宝贝正在路上~", Toast.LENGTH_SHORT).show()
//                buy_succeed=true
//                delete()
//                buy_succeed=false
//                activity?.runOnUiThread {
//                    tv_settlement.text="结算（${choosenum}）"
//                    tv_show_price.text="共计￥${format.format(total)}"
//                }
//                adapter?.notifyDataSetChanged()
//            }
//        }
//    }
override fun onHiddenChanged(hidden: Boolean) {
    super.onHiddenChanged(hidden)
    if (hidden) {
        initSearch()
       sleep(200)//在初始化数据的时候让后续程序暂停执行，数据未读取完成就要显示
        gettotal()//计算价格
        resh()
    }
}
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initSearch()
        sleep(200)//在初始化数据的时候让后续程序暂停执行，数据未读取完成就要显示
        gettotal()//计算价格
        //使用Recycler
        val mRecyclerView = activity?.findViewById<RecyclerView>(R.id.rv_store)
        val layoutManager = LinearLayoutManager(context)
        if (mRecyclerView != null) {
            mRecyclerView.layoutManager = layoutManager
        }
        val adapter = context?.let { gooseAdapter(it,gooselist) }
        if (mRecyclerView != null) {
            mRecyclerView.adapter = adapter
        }
        if (adapter != null) {
            itemcount = adapter.itemCount
        }//获取宝贝总数
        activity?.runOnUiThread {
            total_goose_num.text = "共${itemcount}件宝贝"
            tv_settlement.text = "结算（${choosenum}）"
            tv_show_price.text = "共计￥${total}"
        }

        ck_all.setOnClickListener {//全选
            var n = gooselist.size - 1
            if (ck_all.isChecked) {
                for (i in 0..n) {
                    gooselist[i].choose = true
                }
            } else {
                for (i in 0..n) {
                    gooselist[i].choose = false
                }
            }
            gettotal()
            activity?.runOnUiThread {
                tv_settlement.text = "结算（${choosenum}）"
                tv_show_price.text = "共计￥${format.format(total)}"
            }
            if (adapter != null) {
                adapter.notifyDataSetChanged()
            }
        }

        manager.setOnClickListener {//管理

            if (manager.text == "管理") {
                activity?.runOnUiThread {
                    manager.text = "完成"
                    tv_settlement.text = "删除"
                    tv_show_price.text = ""
                }
            } else {
                activity?.runOnUiThread {
                    tv_settlement.text = "结算（${choosenum}）"
                    tv_show_price.text = "共计￥${format.format(total)}"
                    manager.text = "管理"
                }
            }
            if (adapter != null) {
                adapter.notifyDataSetChanged()
            }
        }

        tv_settlement.setOnClickListener {
            if (tv_settlement.text == "删除") {
                delete()
                activity?.runOnUiThread {
                    total_goose_num.text = "共${itemcount}件宝贝"
                }
                if (adapter != null) {
                    adapter.notifyDataSetChanged()
                }
            } else {
                if (choosenum > 0) {
                    //val intent = Intent(context, buy::class.java)
                    var bundle = Bundle()
                    bundle.putDouble("total_price", total)
                    val idlist: ArrayList<Int> = ArrayList<Int>()
                    val namelist: ArrayList<String> = ArrayList<String>()
                    val pricelist: ArrayList<Double> = ArrayList<Double>()
                    val numlist: ArrayList<Int> = ArrayList<Int>()
                    val piclist: ArrayList<String> = ArrayList<String>()
                    var n = gooselist.size - 1
                    for (i in 0..n) {
                        if (gooselist[i].choose) {
                            idlist.add(gooselist[i].id)
                            namelist.add(gooselist[i].goosename)
                            pricelist.add(gooselist[i].price)
                            numlist.add(gooselist[i].num)
                            piclist.add(gooselist[i].goosepic)
                        }
                    }
                    var price: DoubleArray = DoubleArray(10)
                    n = pricelist.size - 1
                    for (i in 0..n) {
                        price[i] = pricelist[i]
                    }
                    bundle.putIntegerArrayList("idlist", idlist)
                    bundle.putStringArrayList("namelist", namelist)
                    bundle.putDoubleArray("pricelist", price)
                    bundle.putIntegerArrayList("numlist", numlist)
                    bundle.putStringArrayList("piclist", piclist)
                   // intent.putExtras(bundle)
                    //startActivityForResult(intent, 1)
                    val  intent = Intent(context,buy::class.java).apply {
                        putExtras(bundle)
                    }
                    myActivityLauncher.launch(intent)
                }

            }
        }
    }

    fun delete(){//管理删除，或者购买成功后。更新界面和数据库
        if(tv_settlement.text == "删除" || buy_succeed){
            var n=gooselist.size-1
            var i=0
            do {
                if (gooselist[i].choose) {
                    do_delete(gooselist[i].id)
                    total -= (gooselist[i].price) * (gooselist[i].num)
                    gooselist.removeAt(i)
                    n--
                    choosenum--
                    itemcount--
                } else {
                    i++
                }

            } while (i <= n)
        }
    }

    //计算总价和一共有的宝贝
    fun gettotal(){
        total=0.0
        choosenum=0
        var n=gooselist.size-1
        for(i in 0..n){
            if(gooselist[i].choose) {
                total += gooselist[i].num * gooselist[i].price
                choosenum++
            }
        }
    }
    fun print(){
        Toast.makeText(context, "该宝贝不能减少了呦~", Toast.LENGTH_SHORT).show()
    }
    fun do_delete(index:Int){
        val us = "http://192.168.43.140:8080/aaa_war_exploded/delete_shopcart.jsp"
        thread {
            var url = URL(us)
            try {
                val client = OkHttpClient()
                val responseBody = FormBody.Builder()
                    .add("id", URLEncoder.encode("${index}", "UTF-8"))
                    .build()
                val request = Request.Builder()
                    .url(url)
                    .post(responseBody)
                    .build()
                client.newCall(request).execute()
            } catch (e: Exception )
            {
                e.printStackTrace();
            }
        }
    }

    fun initSearch()
    {
        gooselist.clear()
        val us = "http://192.168.43.140:8080/aaa_war_exploded/shopcart.jsp"
        thread {
            var url = URL(us)
            val connection = url.openConnection() as HttpURLConnection
            try {
                connection.connectTimeout = 8000
                connection.readTimeout = 8000
                connection.requestMethod = "POST"

                connection.setRequestProperty("Accept-Charset", "UTF-8" )
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
                connection.connectTimeout = 8000
                connection.readTimeout = 8000
                val input = connection.inputStream
                val reader = BufferedReader(InputStreamReader(input) )

                var src : String = ""
                var id : Int = 0
                var name:String = ""
                var price:Double = 0.0
                var i = 0
                reader.use {
                    reader.forEachLine {
                        if(it.length > 0) {
                            if( i == 0)
                                id = it.trim().toInt()
                            else if( i == 1)
                                name = it
                            else if ( i == 2)
                                price = it.trim().toDouble()
                            else if(i  == 3)
                                src = it
                            i++

                            if(i == 4){
                                i=0
                                gooselist.add(gooseInfo(id, false, name, price,src,1))
                            }
                        }
                    }
                }
            } catch (e: Exception )
            {
                e.printStackTrace();
            } finally {
                connection.disconnect()
            }
        }

    }
    inner class gooseAdapter(val content: Context, private val gooselist: ArrayList<gooseInfo>) :
        RecyclerView.Adapter<gooseAdapter.MyViewHolder>() {


        private var ItemClickListenr:ItemClickListenr?=null
        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): MyViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(
                R.layout.gouwuche_shangping,
                parent,
                false
            )
            return MyViewHolder(view)
        }

        fun setOnItemClickLinstenner(listenr: ItemClickListenr){
            this.ItemClickListenr=listenr
        }

        override fun getItemCount(): Int = gooselist.size ?: 0
        override fun onBindViewHolder(holder: gooseAdapter.MyViewHolder, position: Int) {
            val goose = gooselist[position]
            holder.goosecheck.isChecked = goose.choose
            holder.goosename.text = goose.goosename
            Glide.with(content)
                .load(goose.goosepic)
                .into(holder.goosepic)
            holder.gooseprice.text =(format.format((goose.price) * (goose.num))).toString()
            holder.goosenum.text=goose.num.toString()
            holder.goosesub.setImageResource(R.drawable.goose_sub)
            holder.gooseadd.setImageResource(R.drawable.goose_add)

            holder.itemView.setOnClickListener {

            }
            holder.gooseadd.setOnClickListener{//商品加1
                goose.num++
                if(goose.choose) {//当商品未被选中时，加减对其总价不影响
                    total+=goose.price
                    activity?.runOnUiThread {
                        tv_show_price.text = "共计${format.format(total)}"
                    }
                }
                notifyDataSetChanged()
            }
            holder.goosesub.setOnClickListener{//商品减一
                if(goose.num == 1)
                    print()
                else {
                    goose.num--
                    if(goose.choose) {
                        total-=goose.price
                        activity?.runOnUiThread {
                            tv_show_price.text = "共计${format.format(total)}"
                        }
                    }
                    notifyDataSetChanged()
                }
            }
            holder.goosecheck.setOnClickListener {//单件选择
                goose.choose=!goose.choose
                if(goose.choose){
                    total+=(goose.price)*(goose.num)
                    choosenum++
                }
                else{
                    total-=(goose.price)*(goose.num)
                    choosenum--
                }
                if(manager.text=="管理") {
                    activity?.runOnUiThread {
                        tv_show_price.text="共计${format.format(total)}"
                        tv_settlement.text="结算（${choosenum}）"
                    }
                }
                notifyDataSetChanged()
            }
        }



        inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val goosecheck: CheckBox = itemView.findViewById(R.id.goose_check)
            val goosepic: ImageButton = itemView.findViewById(R.id.goose_picture)
            val goosename: TextView = itemView.findViewById(R.id.goose_name)
            val goosenum: TextView = itemView.findViewById(R.id.goose_num)
            val gooseprice: TextView = itemView.findViewById(R.id.goose_price)
            val goosesub: ImageView = itemView.findViewById(R.id.goose_sub)
            val gooseadd: ImageView = itemView.findViewById(R.id.goose_add)
        }
    }


}